﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;

namespace Northwind_ObjectContext
{
    public class CustomerUtilities
    {
        public static void InsetCustomer(Customer custToAdd)
        {
            NorthwindEntities dataContext = new NorthwindEntities();
            using (dataContext)
            {
                dataContext.Customers.AddObject(custToAdd);
                dataContext.SaveChanges(); 
            }            
        }

        public static Customer GetCustomerById(string id)
        {
            NorthwindEntities dataContext = new NorthwindEntities();
            {
                Customer customer = dataContext.Customers.FirstOrDefault(c => c.CustomerID == id);
                dataContext.Detach(customer);
                return customer;
            }
        }

        public static void ModifyCustomer(Customer custToMod)
        {
            using (NorthwindEntities context = new NorthwindEntities())
            {
                context.Attach(custToMod);

                context.ObjectStateManager.GetObjectStateEntry(custToMod).SetModified();
                context.Refresh(System.Data.Objects.RefreshMode.ClientWins, custToMod);               

                context.SaveChanges();
            }            
        }


        public static void DeleteCustomer(Predicate<Customer> predicate)
        {
            using (NorthwindEntities dataContext = new NorthwindEntities())
            {
                var customers = dataContext.Customers.ToList();

                var customersToDelete =  customers.Where(c => predicate(c));

                foreach (var customer in customersToDelete)
                {
                    dataContext.Customers.DeleteObject(customer);
                }
                dataContext.SaveChanges();
            }
        }
    }
}
